package com.mikhailenko.transportMVC.service.es.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mikhailenko.transportMVC.exeption.es.LayerNotFoundExeption;
import com.mikhailenko.transportMVC.model.es.LayerEntity;
import com.mikhailenko.transportMVC.repository.es.LayerRepository;
import com.mikhailenko.transportMVC.service.es.LayerService;

@Service
public class LayerServiceImpl implements LayerService {

    @Autowired
    private LayerRepository layerRepository;
    
    @Override
    public LayerEntity create(LayerEntity layer) {
        LayerEntity createdLayer = layer;
        return layerRepository.saveAndFlush(createdLayer);
    }

    @Override
    public LayerEntity delete(int id) throws LayerNotFoundExeption {
        LayerEntity deletedLayer = layerRepository.findOne(id);
        
        if (deletedLayer == null){
            throw new LayerNotFoundExeption();
        }
            
        layerRepository.delete(deletedLayer);
        return deletedLayer;
    }

    @Override
    public List<LayerEntity> findAll() {
        return layerRepository.findAll();
    }

    @Override
    public LayerEntity update(LayerEntity layer) throws LayerNotFoundExeption {
        LayerEntity updatedLayer = layerRepository.findOne(layer.getId());
        
        if (updatedLayer == null){
            throw new LayerNotFoundExeption();
        }
            
        updatedLayer.setCountOfBlocks(layer.getCountOfBlocks());
        updatedLayer.setEs(layer.getEs());
        
        return updatedLayer;
    }

    @Override
    public LayerEntity findById(int id) {
        return layerRepository.findOne(id);
    }

	@Override
	public List<LayerEntity> findByEsId(int id) {
		return layerRepository.findByEsId(id);
	}

}
